import Taro from '@tarojs/taro';
import { useEffect, useRef } from 'react';
import { connect } from 'react-redux';

const getPage = () => {
  let currentPages = Taro.getCurrentPages();
  return currentPages[currentPages.length - 1];
};

const getTabBar = () => {
  return getPage()?.getTabBar();
};

const CartNum = ({ dispatch, carNum }) => {
  const tabBar = useRef(getTabBar());

  // 首次加载时获取下数据
  useEffect(() => {
    if (carNum) {
      return;
    }

    dispatch({
      type: 'productList/getCarNum',
      payload: {},
    });
  }, []);

  // 每次 购物车数量变更时, 更新下数据
  useEffect(() => {
    tabBar.current?.setData({ banner: { carNum } });
  }, [carNum]);

  // 离开页面, 清除数据
  useEffect(() => {
    return () => {
      tabBar.current = null;
    };
  }, []);

  return null;
};

export default connect(({ loading, productList }) => ({
  carNum: productList.carNum,

  loading,
}))(CartNum);
